package com.nowcoder.community.service;

import com.nowcoder.community.dao.CommentMapper;
import com.nowcoder.community.dao.DiscussPostMapper;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private DiscussPostMapper discussPostMapper;

    public int findCommentRowsByEntity(int entityType, int entityId) {
        return commentMapper.selectCommentRowsByEntity(entityType, entityId);
    }

    public List<Comment> findCommentsByEntity(int entityType, int entityId, int limit, int offset) {
        return commentMapper.selectCommentsByEntity(entityType, entityId, limit, offset);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment) {
        if (comment == null) {
            throw new IllegalArgumentException("参数错误！");
        }
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));

        // 增加评论
        int rows = commentMapper.insertComment(comment);

        // 更新帖子的评论数
        if (comment.getEntityType() == CommunityConstant.ENTITY_TYPE_POST) {
            discussPostMapper.updateCommentCount(comment.getEntityId(),
                    commentMapper.selectCommentRowsByEntity(CommunityConstant.ENTITY_TYPE_POST, comment.getEntityId()));
        }

        return rows;
    }

    public int findCommentRowsByUser(int userId) {
        return commentMapper.selectCommentRowsByUser(userId);
    }

    public List<Comment> findCommentsByUser(int userId, int limit, int offset) {
        return commentMapper.selectCommentsByUser(userId, limit, offset);
    }

    public Comment findCommentById(int id) {
        return commentMapper.selectCommentById(id);
    }

}
